<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayableClearanceModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Clearance extends Controller
{
    /**
     * 清关列表
     */
    public function list(Request $request)
    {
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');
        $take_order = $request->input('take_order', '');
        $destination = $request->input('destination', '');
        $agent_id = $request->input('agent_id', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableClearanceModel::with(['createAdmin', 'agent', 'takeOrder']);

        if ($date_start && $date_end) {
            $query->whereBetween('date', [$date_start, $date_end]);
        }

        if ($take_order) {
            $query->whereHas('takeOrder', function($query) use ($take_order) {
                $query->where('sn', $take_order);
            });
        }

        if ($destination) {
            $query->where('destination', 'like', "%{$destination}%");
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'date' => $item->date,
                    'take_order_id' => $item->take_order_id,
                    'take_order' => $item->takeOrder->sn ?? '',
                    'destination' => $item->destination,
                    'package_num' => $item->package_num,
                    'weight' => $item->weight,
                    'channel' => $item->channel,
                    'unit_price' => $item->unit_price,
                    'delivery_fee' => $item->delivery_fee,
                    'total_amount' => $item->total_amount,
                    'remarks' => $item->remarks,
                    'status' => $item->status,
                    'status_name' => PayableClearanceModel::STATUS_LIST[$item->status] ?? '',
                    'pay_amount' => $item->pay_amount,
                    'created_admin_id' => $item->created_admin_id,
                    'created_admin_name' => $item->createAdmin->name ?? '',
                    'created_at' => $item->created_at->format('Y-m-d H:i:s')
                ];
            });

        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加清关记录
     */
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'date' => 'required|date',
            'take_order' => 'required|string',
            'destination' => 'required|string',
            'package_num' => 'required|integer|min:0',
            'weight' => 'required|numeric|min:0',
            'channel' => 'required|string',
            'unit_price' => 'required|numeric|min:0',
            'delivery_fee' => 'required|numeric|min:0',
            'total_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $take_order = $request->input('take_order', '');
        $take_order = TakeOrderModel::where('sn', $take_order)->first();
        if (!$take_order) {
            return $this->error('提单号不存在');
        }

        try {
            $clearance = new PayableClearanceModel();
            $clearance->agent_id = $request->input('agent_id');
            $clearance->date = $request->input('date');
            $clearance->take_order_id = $take_order->id;
            $clearance->destination = $request->input('destination');
            $clearance->package_num = $request->input('package_num');
            $clearance->weight = $request->input('weight');
            $clearance->channel = $request->input('channel');
            $clearance->unit_price = $request->input('unit_price');
            $clearance->delivery_fee = $request->input('delivery_fee');
            $clearance->total_amount = $request->input('total_amount');
            $clearance->remarks = trim($request->input('remarks', ''));
            $clearance->status = PayableClearanceModel::STATUS_UNPAID;
            $clearance->pay_amount = 0;
            $clearance->created_admin_id = $request->get('auth')->id;
            $clearance->save();

            return $this->success($clearance);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新清关记录
     */
    public function update(Request $request, $id)
    {
        $clearance = PayableClearanceModel::find($id);
        if (!$clearance) {
            return $this->error('清关记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'date' => 'required|date',
            'take_order' => 'required|string',
            'destination' => 'required|string',
            'package_num' => 'required|integer|min:0',
            'weight' => 'required|numeric|min:0',
            'channel' => 'required|string',
            'unit_price' => 'required|numeric|min:0',
            'delivery_fee' => 'required|numeric|min:0',
            'total_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $take_order = $request->input('take_order', '');
        $take_order = TakeOrderModel::where('sn', $take_order)->first();
        if (!$take_order) {
            return $this->error('提单号不存在');
        }

        try {
            $clearance->agent_id = $request->input('agent_id');
            $clearance->date = $request->input('date');
            $clearance->take_order_id = $take_order->id;
            $clearance->destination = $request->input('destination');
            $clearance->package_num = $request->input('package_num');
            $clearance->weight = $request->input('weight');
            $clearance->channel = $request->input('channel');
            $clearance->unit_price = $request->input('unit_price');
            $clearance->delivery_fee = $request->input('delivery_fee');
            $clearance->total_amount = $request->input('total_amount');
            $clearance->remarks = trim($request->input('remarks', ''));
            $clearance->save();

            return $this->success($clearance);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除清关记录
     */
    public function delete($id)
    {
        $clearance = PayableClearanceModel::find($id);
        if (!$clearance) {
            return $this->error('清关记录不存在');
        }

        if ($clearance->status != PayableClearanceModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $clearance->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

} 